/*
 * @Description: 错误捕获
 * @Autor: HuiSir<www.zuifengyun.com>
 * @Date: 2022-05-19 16:12:51
 * @LastEditTime: 2022-06-06 14:10:46
 */
import Koa from 'koa'
import { print, useResult } from 'tcp-micro-service'

const { error } = useResult()

export default (app: Koa) => {

    // 后台错误捕获
    app.on('error', (err) => {
        print.error(err)
    })

    // 前台错误捕获
    const catchMidware: Koa.Middleware<Promise<void>> = async (ctx, next) => {
        try {
            // 返回格式,默认添加charset=utf-8
            // 对象默认为application/json，故此处可不配置
            // 后续有特例可在此判断重置
            ctx.type = 'application/json'
            await next()
        } catch (err: any) {
            //前台捕获
            const status = err.statusCode || 500
            ctx.status = status
            ctx.type = 'application/json'
            ctx.body = error({
                status,
                msg: err.message,
            })
            //后台捕获
            const statusWhiteList = [401, 403, 404, 200]
            //如果错误被try...catch捕获，就不会触发error事件，故需要使用emit方法
            !statusWhiteList.includes(status)
                && ctx.app.emit('error', err, ctx)
        }
    }

    return catchMidware
}
